//
//  CZComposeViewController.swift
//  Blog
//
//  Created by whitcast on 16/7/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZComposeViewController: UIViewController {
    // MARK: -- 懒加载
    private lazy var titleLabel:UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 17)
        label.numberOfLines = 0
        label.textAlignment = .Center
        // 获取用户名
        if let name = CZUserAccountViewModel.shareUserAccount.userAccount?.name{
            let title = "发微博\n\(name)"
            let attributeStr = NSMutableAttributedString(string: title)
            // 获取名字的范围
            let range = (title as NSString).rangeOfString(name)
            
            attributeStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
            label.attributedText = attributeStr
        }else {
            label.text = "发微博"
        }
        
        label.sizeToFit()
        
        return label
    }()
    // 右侧按钮（发送按钮）
    private lazy var rightButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        button.size = CGSize(width: 45, height: 30)

        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

       view.backgroundColor = UIColor.whiteColor()
    }
    
    // 添加自定义textView
    private lazy var textView: CZComposeTextView = {
        let view = CZComposeTextView()
        view.delegate = self
        view.placeHolder = "敲代码敲代码敲代码"
        view.font = UIFont.systemFontOfSize(15)
        // 垂直方向弹簧效果
        view.alwaysBounceHorizontal = true
        return view
    }()
    
    // toolbar
    private lazy var toolBar: CZComposeToolBar = {
        let view = CZComposeToolBar(frame: CGRectZero)
        return view
    }()
    
    // 配图
    private lazy var pictureView: CZComposePictureView = {
        let view = CZComposePictureView()
        return view
    }()
    
    // 表情键盘
    private lazy var keyBoard: CZEmoticonKeyBoard = {
        let view = CZEmoticonKeyBoard()
        // 设置视图大小
       view.size = CGSize(width: self.textView.width, height: 216)
        return view
    }()
    
    private func setupUI() {
        // 监听键盘改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)

        setupNavUI()
        view.addSubview(textView)
        view.addSubview(toolBar)
        view.addSubview(pictureView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(self.toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(30)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.leading.equalTo(textView).offset(10)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }

        toolBar.selectedToolBarButtonClosure = { [weak self] (type: CZComposeToolBarButtonType) in
            switch type {
            case .Picture:
                print("图片")
                
            case .Mention:
                print("@")
            case .Trend:
                print("话题")
            case .Emoticon:
                print("表情")
                
            case .Add:
                print("加号")
            }
            
        }
        pictureView.didSelectedAddClosure = {[weak self] in
            // 打开图片选择器
            self?.didSelectedPicture()
        }
    }
    
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancleAction")
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    @objc private func keyboardChangeFrame(noti: NSNotification) {
        // 获取屏幕的frame
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 获取动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        // 更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - ScreenHight)
            
        }
        // 执行动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func cancleAction() {
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    @objc private func sendAction() {
        // 带图片微博上传接口
        if pictureView.images.count > 0 {
            let image = pictureView.images.first!
            let accessToken = CZUserAccountViewModel.shareUserAccount.accessToken!
            let text = textView.text!
            SVProgressHUD.show()
            CZNetworkTools.sharedTools.upload(accessToken, status: text, image: image, callBack: { (response, error) -> () in
                if error != nil {
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    return
                }else {
                    SVProgressHUD.showSuccessWithStatus("发送成功")
                }
            })
        }else {
            //  发送文字微博接口
            let accessToken = CZUserAccountViewModel.shareUserAccount.accessToken!
            let text = textView.text!
            SVProgressHUD.show()
            CZNetworkTools.sharedTools.update(accessToken, status: text) { (response, error) -> () in
                if error != nil {
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    return
                }
                
                
                //  发送成功
                SVProgressHUD.showSuccessWithStatus("发送成功")

        }
        
        
        
        }
    
    }
}

extension CZComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    // 表情键盘处理
    func didSelectedEmoticon() {
        // 显示表情键盘或者系统键盘
        if textView.inputView == nil {
            textView.inputView = keyBoard
            // 设置键盘显示的icon
            toolBar.showEmotionIcon(true)
        }else {
            textView.inputView = nil
            // 设置键盘显示的icon
            toolBar.showEmotionIcon(false)

        }
        // 获取第一响应者
        textView.becomeFirstResponder()
        // 重新刷新inputView
        textView.reloadInputViews()
    }
    
    // 图片处理
    func didSelectedPicture() {
        let imagePictureCtr = UIImagePickerController()
        // 设置代理
        imagePictureCtr.delegate = self
        // 判断是否支持这个来源类型
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            imagePictureCtr.sourceType = .Camera
            print("支持相机")
        }else {
            imagePictureCtr.sourceType = .PhotoLibrary
            print("不支持相机，使用的图库")
        }
        // 判断是否支持前置或者后置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("支持前置摄像头")
        }else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("支持后置摄像头")
        }else {
            print("前后置摄像头不支持")
        }
        // 允许用户编辑
        presentViewController(imagePictureCtr, animated: true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //  获取压缩后的图片
        let scaleImage = image.scaleImageWithScaleWidth(200)
        print(scaleImage)
        
        pictureView.addImage(scaleImage)
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
}

extension CZComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        // 根据文本内容判断发送按钮是否可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}
